<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SMSLog;
use App\User;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;

class CommonController extends Controller{

    /**
     * 获取书籍分类数据
     * */
    public function getBookType(){
        $data['bookType'] = get_bookType(0);
        return jsonSuccessData($data);
    }

    /**
     * 发送邮箱验证码
     * @param string email
     * @param int type 1注册 2登陆 3找回密码
     *
     * */
    public function sendMailCode()
    {
        $email = Input::get('email');
        $type = Input::get('type',1);
        if (!$email) {
            return echoJson("邮箱不正确",1002);
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return echoJson("非法邮箱格式",1002);
        }

        $is_exists = User::getUserInfoByEmail($email);

        if ($type == 1 && $is_exists){
            return echoJson('该邮箱已注册',1002);
        }
        if (($type == 2 || $type == 3) && !$is_exists){
            return echoJson('该邮箱未注册',1002);
        }

        $result = sendSmsCode($email,$type,'mail');

        return echoJson($result['msg'],$result['code']);
    }

    /*
     * 验证邮箱验证码
     * */
    public function checkMailCode()
    {
        $code = Input::get('code');
        $email = Input::get('email');
        $type = Input::get('type',1);
        if (!$email) {
            return echoJson("邮箱不正确",1002);
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return echoJson("非法邮箱格式",1002);
        }

        $result = checkSmsCode($email,$code,$type);

        if ($result['code'] == 200){
            return echoJson($result['msg'],$result['code'],['token'=>getTokenByCode($code)]);
        }else{
            return echoJson($result['msg'],$result['code']);
        }
    }
}